package com.liuweijiaoyu.demo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.liuweijiaoyu.demo.util.OnlineQuestion;
import com.liuweijiaoyu.demo.util.QuestionTemplate;
import com.liuweijiaoyu.demo.widgets.HybirdWebView;
import com.liuweijiaoyu.demo.widgets.WebViewClientWrapper;
import com.liuweijiaoyu.demo.widgets.oxny.DraftPaper;
import com.onyx.android.sdk.api.device.epd.EpdController;

import java.io.IOException;
import java.util.Hashtable;
import java.util.List;


/**
 * 看题，做题
 */
public class HkQuestionActivity extends Activity {
    /**
     * 翻页参数：下一题
     */
    private static final String PAGE_NEXT = "next";
    private static final String PAGE_PREVIEW = "preview";
    private static final String PAGE_ANSWER_SHEET = "showAnswerSheet";
    /**
     * 加载题目的webview
     */
    public HybirdWebView mHwvWeb;
    /**
     * 手写功能view
     */
    public DraftPaper mDpVView;
    /**
     * 显示答案解析按钮
     */
    private TextView mTvShowAnswer;

    /**
     * 是否是做题模式
     */
    public boolean isWriteAble = true;


    /**
     * 作业bean
     */
    private OnlineQuestion questionList;
    /**
     * 当前题目数据
     */
    private OnlineQuestion.QuestionItem currentQuestion;
    /**
     * 当前作业题目列表
     */
    private List<OnlineQuestion.QuestionItem> mQuestionItemList;
    /**
     * 当前题目索引，从0开始
     */
    public int questionIndex = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_dohomework);
        questionList = new OnlineQuestion();
        mQuestionItemList = questionList.parse();
        currentQuestion = mQuestionItemList.get(questionIndex);

        initWebView();
        mDpVView = (DraftPaper) findViewById(R.id.dpv_qt);
        mTvShowAnswer = (TextView) findViewById(R.id.tv_add2Error);
        if (mTvShowAnswer != null) {
            mTvShowAnswer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!isChoice(currentQuestion)) {
                        //禁用手写模式，通知用户刷新ui，之后重新开启手写模式
                        mDpVView.leaveScribbleMode();
                        mHwvWeb.runJs("showAnswer");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mDpVView.enterScribbleMode();
                            }
                        }, 200);
                    }else {
                        mHwvWeb.runJs("showAnswer");
                    }
                }
            });
        }
        showQuestion(questionIndex);
    }


    private void initWebView() {
        mHwvWeb = (HybirdWebView) findViewById(R.id.wv);

        mHwvWeb.getSettings().setJavaScriptEnabled(true);
        mHwvWeb.getSettings().setUseWideViewPort(true);
        mHwvWeb.getSettings().setAppCacheEnabled(true);
        mHwvWeb.getSettings().setDatabaseEnabled(true);
        mHwvWeb.setWebViewClient(new WebViewClientWrapper());
        mHwvWeb.setActionListener(mActionListener);
        EpdController.setWebViewContrastOptimize(mHwvWeb, false);
    }


    private HybirdWebView.WebViewActionListener mActionListener = new HybirdWebView.WebViewActionListener() {

        @Override
        public void onSizeChange(int width, int height) {

        }

        @Override
        public void onDomReady() {

        }

        @Override
        public void onCallMethod(String methodName,
                                 Hashtable<String, String> paramsMap) throws Exception {
         onCallMethodImpl(methodName, paramsMap);
        }

        @Override
        public void onPageFinished() {
            Log.d("qt","onPageFinished");
            //此处页面并没有渲染完毕，开启手写后会导致页面无法显示
            /*if (isWriteAble && !isChoice(currentQuestion)) {
                if (mDpVView != null) {
                    String as = currentQuestion.getAnswer();
                    if(as!=null &&!"".equals(as.trim())) {
                        mDpVView.setPathString(as);
                    }

                    ((View) mDpVView).setVisibility(View.VISIBLE);
                }
                Log.d("qt","enterScribbleMode");
                mDpVView.enterScribbleMode();
            }*/
        }
    };
    @Override
    protected void onPause() {
        super.onPause();
        if (mDpVView != null) {
            mDpVView.leaveScribbleMode();
        }
    }


    /**
     * webview js回调接口
     *
     * @param methodName 接口方法名
     * @param paramsMap  参数列表
     * @return
     */

    protected boolean onCallMethodImpl(String methodName, Hashtable<String, String> paramsMap) {
        if ("onLoad".equals(methodName)) {
            if (isWriteAble && !isChoice(currentQuestion)) {
                if (mDpVView != null) {
                    String as = currentQuestion.getAnswer();
                    if(as!=null &&!"".equals(as.trim())) {
                        mDpVView.setPathString(as);
                    }
                    ((View) mDpVView).setVisibility(View.VISIBLE);
                }
                //TODO 页面渲染完毕开启手写模式。
                // 由于此处无法准确获取webview渲染完毕事件，所以暂做延迟处理。
                // 如果延迟的时间太短会出现页面渲染不完整问题。
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mDpVView.enterScribbleMode();
                    }
                }, 100);
            }
        } else if (PAGE_NEXT.equals(methodName)) {

            if (mDpVView != null && ((View) mDpVView).getVisibility() == View.VISIBLE) {
                ((View) mDpVView).setVisibility(View.GONE);
            }
            //保存答案和耗时
            if (isWriteAble) {
                if (!isChoice(currentQuestion)) {
                    mDpVView.leaveScribbleMode();
                }
                saveQuestion();
                if (questionIndex < (mQuestionItemList.size() - 1)) {
                    //跳转到下一题
                    questionIndex++;
                    showQuestion(questionIndex);
                } else {//当前是最后一道题，跳转到答题卡
                    //保存答案和耗时
                    if (!isChoice(currentQuestion)) {
                        mDpVView.leaveScribbleMode();
                    }
                    saveQuestion();
                    showAnswerSheet();
                }
            } else {
                if (questionIndex < (mQuestionItemList.size() - 1)) {
                    //跳转到下一题
                    questionIndex++;
                    showQuestion(questionIndex);
                } else {//当前是最后一道题，跳转到答题卡
                    //保存答案和耗时
                    showAnswerSheet();
                }
            }

            return true;
        } else if (PAGE_PREVIEW.equals(methodName)) {
            if (questionIndex <= 0) {
                return true;
            }
            if (mDpVView != null && ((View) mDpVView).getVisibility() == View.VISIBLE) {
                ((View) mDpVView).setVisibility(View.GONE);
            }
            //保存答案和耗时
            if (isWriteAble) {
                if (!isChoice(currentQuestion)) {
                    mDpVView.leaveScribbleMode();
                }
                saveQuestion();
                questionIndex--;
                showQuestion(questionIndex);
            } else {
                questionIndex--;
                showQuestion(questionIndex);
            }
            return true;
        } else if (PAGE_ANSWER_SHEET.equals(methodName)) {
            //保存答案和耗时
            if (isWriteAble) {
                if (!isChoice(currentQuestion)) {
                    mDpVView.leaveScribbleMode();
                }
                saveQuestion();
            }
            showAnswerSheet();
            return true;
        }
        return true;
    }


    /**
     * 让webview加载指定题
     *
     * @param index 题索引
     */
    protected void showQuestion(int index) {
        currentQuestion=mQuestionItemList.get(index);
        //显示答案
        String showAnswer = "YES";
        //显示答题卡
        String showAnswerSheet = "YES";
        //生成题目模板并加载模板
        try {
            String template = QuestionTemplate.getIns().getTemplate(this,currentQuestion , showAnswer, showAnswerSheet, String.valueOf(index + 1), String.valueOf(3));
            mHwvWeb.loadDataWithBaseURL("file:///android_asset/", template, "text/html", "UTF-8", "");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 请求服务器保存题目数据
     */
    protected void saveQuestion() {
        updateQuestion();
        //保存
    }


    /**
     * 将最新的状态更新到当前题模型中，子类可重写
     */
    protected void updateQuestion() {
        if (!isChoice(currentQuestion)) {
            //解答题答案为手写的笔迹
            currentQuestion.setAnswer(mDpVView.getPathString());
        }
    }


    /**
     * 跳转到答题卡，需子类重写
     */
    protected void showAnswerSheet() {
        Toast.makeText(this, "显示答题卡", Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断当前题型是否是选择题，单选或多选
     *
     * @return true 选择题，false 解答题
     */
    protected boolean isChoice(OnlineQuestion.QuestionItem qt) {
        if (qt.getQuestionType() == 1 || qt.getQuestionType() == 2) {
            return true;
        }
        return false;
    }

}
